#include "MainWindow.h"

#include "../core/PDFManager.h"
#include <QDebug>
#include <QGraphicsPixmapItem>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    initUI();
    createActions();
    createMenus();
    createToolBars();
}

MainWindow::~MainWindow()
{
}

void MainWindow::initUI()
{
    m_layout = new QVBoxLayout;
    m_view = new QGraphicsView(this);

    m_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    m_view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    // Add the view to the layout
    m_layout->addWidget(m_view);

    // Create a new QWidget that will serve as the central widget
    QWidget* centralWidget = new QWidget(this);
    centralWidget->setLayout(m_layout);

    // Set the central widget of the QMainWindow
    this->setCentralWidget(centralWidget);
}


void MainWindow::createActions()
{
    m_newAction = new QAction(QIcon("://icons/new.png"), tr("&New"), this);
    connect(m_newAction, &QAction::triggered, this, &MainWindow::newFile);

    m_openAction = new QAction(QIcon(":/icons/open.png"), tr("&Open"), this);
    connect(m_openAction, &QAction::triggered, this, &MainWindow::openFile);

    m_saveAction = new QAction(QIcon(":/icons/save.png"), tr("&Save"), this);
    connect(m_saveAction, &QAction::triggered, this, &MainWindow::saveFile);
}

void MainWindow::createMenus()
{
    m_fileMenu = menuBar()->addMenu(tr("&File"));
    m_fileMenu->addAction(m_newAction);
    m_fileMenu->addAction(m_openAction);
    m_fileMenu->addAction(m_saveAction);
}

void MainWindow::createToolBars()
{
    m_fileToolBar = addToolBar(tr("File"));
    m_fileToolBar->addAction(m_newAction);
    m_fileToolBar->addAction(m_openAction);
    m_fileToolBar->addAction(m_saveAction);
}

void MainWindow::newFile()
{
    // 这里可以添加用于创建新文件的代码
}

void MainWindow::openFile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("PDF Files (*.pdf)"));

    if (!filename.isEmpty())
    {
        PDFManager pdfManager;
        Poppler::Document* document = pdfManager.loadPdfFile(filename);

        if (document)
        {
            QGraphicsScene* scene = new QGraphicsScene(this);
            double yPosition = 0.0; // 初始化 y 位置

            for (int i = 0; i < document->numPages(); ++i)
            {
                QImage image = document->page(i)->renderToImage();
                QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(image));

                // 设置 item 的 y 位置，并更新下一页的 y 位置
                item->setY(yPosition);
                yPosition += image.height() + 10; // 添加 10 的垂直间距

                scene->addItem(item);
            }

            m_view->setScene(scene);
        }
    }
}



void MainWindow::saveFile()
{
    QString fileName = QFileDialog::getSaveFileName(this);
    if (!fileName.isEmpty()) {
        // 这里可以添加用于保存文件的代码
    }
}
